package com.example.stray_animal_management_system.admin.controller;

import com.example.stray_animal_management_system.admin.service.VolunteerApplicationService;
import com.example.stray_animal_management_system.entity.User;
import com.example.stray_animal_management_system.entity.Volunteer;
import com.example.stray_animal_management_system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: panpan
 * @time: 2025/11/8
 */
@RestController
@RequestMapping("/api/admin/volunteer")
public class AdminVolunteerApplicationController {

    @Autowired
    private VolunteerApplicationService volunteerApplicationService;

    @Autowired
    private UserService userService;  // 用于更新用户角色

    /**
     * 管理员查看所有待审核的志愿者申请
     */
    @GetMapping("/pending")
    public Map<String, Object> getPendingApplications() {
        Map<String, Object> res = new HashMap<>();

        // 查询所有待审核的志愿者申请
        List<Volunteer> applications = volunteerApplicationService.lambdaQuery()
                .eq(Volunteer::getStatus, 0)  // 0表示待审核
                .list();

        res.put("code", 200);
        res.put("data", applications);
        return res;
    }

    /**
     * 管理员审核志愿者申请（通过/驳回）
     */
    @PostMapping("/review")
    public Map<String, Object> reviewApplication(@RequestParam("id") Integer id,
                                                 @RequestParam("status") Integer status,  // 1通过，2驳回
                                                 @RequestParam(value = "rejectReason", required = false) String rejectReason) {
        Map<String, Object> res = new HashMap<>();

        // 获取申请
        Volunteer application = volunteerApplicationService.getById(id);
        if (application == null) {
            res.put("code", 404);
            res.put("msg", "申请不存在");
            return res;
        }

        // 更新申请状态
        application.setStatus(status);
        application.setReviewTime(new Date());
        if (status == 2) {
            application.setRejectReason(rejectReason);  // 如果是驳回，设置驳回理由
        }
        volunteerApplicationService.updateById(application);

        // 如果申请通过，更新用户角色为志愿者
        if (status == 1) {
            User user = userService.getById(application.getUserId());
            if (user != null) {
                user.setRoleId(2);  // 2表示志愿者角色
                userService.updateById(user);
            }
        }

        res.put("code", 200);
        res.put("msg", status == 1 ? "申请已通过" : "申请已驳回");
        return res;
    }
}
